﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Threading;
using System.Web.Mvc;
using WebChatApi.Common;

namespace WebChatApi
{
    /// <summary>
    /// Base MVC controller
    /// </summary>
    public class BaseMVCController : Controller
    {
        /// <summary>
        /// The ajax urls
        /// </summary>
        protected List<string> ajaxUrls = new List<string>();

        /// <summary>
        /// The session key_ culture
        /// </summary>
        protected const string sessionKey_Culture = "CultureInfo";

        /// <summary>
        /// The session key_ user key
        /// </summary>
        protected const string sessionKey_UserKey = "UserKey";

        /// <summary>
        /// The session key_ user info
        /// </summary>
        protected const string sessionKey_UserInfo = "UserInfo";

        /// <summary>
        /// The get parameter_ language
        /// </summary>
        protected const string getParameter_Language = "lang";

        /// <summary>
        /// Gets or sets the session user key.
        /// </summary>
        /// <value>The session user key.</value>
        protected Guid? SessionUserKey
        {
            get
            {
                return Session[sessionKey_UserKey] as Guid?;
            }
            set
            {
                Session[sessionKey_UserKey] = value;
            }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="BaseMVCController" /> class.
        /// </summary>
        public BaseMVCController()
        {
            InitializeAjaxUrls();
        }

        /// <summary>
        /// Initializes the ajax urls.
        /// </summary>
        protected virtual void InitializeAjaxUrls()
        {
        }

        /// <summary>
        /// Synchronizes the culture info.
        /// </summary>
        /// <param name="threadCultureToSession">if set to <c>true</c> [thread culture to session].</param>
        protected void SynchronizeCultureInfo(bool threadCultureToSession = true)
        {
            CultureInfo cultureInfo = null;

            var request = this.Request;
            if (request != null)
            {
                cultureInfo = CommonFramework.Instance.GetCultureInfoByCode(request[getParameter_Language]);
            }

            if (cultureInfo != null)
            {
                this.Session[sessionKey_Culture] = cultureInfo;
                Thread.CurrentThread.CurrentCulture = cultureInfo;
            }
            else
            {
                cultureInfo = this.Session[sessionKey_Culture] as CultureInfo;
            }

            if (cultureInfo == null && threadCultureToSession)
            {
                this.Session[sessionKey_Culture] = Thread.CurrentThread.CurrentCulture;
            }
        }

        /// <summary>
        /// Ajaxes the URL collection.
        /// </summary>
        /// <returns>JavaScriptResult.</returns>
        public JavaScriptResult AjaxUrlCollection()
        {
            StringBuilder builder = new StringBuilder("var ajaxUrlCollection=[];");

            foreach (var one in this.ajaxUrls)
            {
                builder.AppendFormat("ajaxUrlCollection['{0}']='{1}';", one, Url.Action(one));
            }

            return JavaScript(builder.ToString());
        }

        /// <summary>
        /// Downloads the file.
        /// </summary>
        /// <param name="fileBytes">The file bytes.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <returns>FileResult.</returns>
        protected FileResult DownloadFile(byte[] fileBytes, string fileName)
        {
            return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
        }
        /// <summary>
        /// Gets the client ip address.
        /// </summary>
        /// <returns>System.String.</returns>
        protected string GetClientIpAddress()
        {
            string ipAddress = this.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(ipAddress))
            {
                ipAddress = this.Request.ServerVariables["REMOTE_ADDR"];
            }
            return ipAddress;
        }

        /// <summary>
        /// Determines whether [is user agent from mobile] [the specified user agent].
        /// </summary>
        /// <param name="userAgent">The user agent.</param>
        /// <param name="defaultValue">if set to <c>true</c> [default value].</param>
        /// <returns><c>true</c> if [is user agent from mobile] [the specified user agent]; otherwise, <c>false</c>.</returns>
        public static bool IsUserAgentFromMobile(string userAgent, bool defaultValue = false)
        {
            return string.IsNullOrWhiteSpace(userAgent) ? defaultValue : (
                    userAgent.IndexOf("ipad", StringComparison.InvariantCultureIgnoreCase) > -1
                    || userAgent.IndexOf("iphone", StringComparison.InvariantCultureIgnoreCase) > -1
                    || userAgent.IndexOf("android", StringComparison.InvariantCultureIgnoreCase) > -1
                    );
        }
    }
}
